import api from '../../../common/api.js'
import mapConfig from '../../../utils/mapConfig';
import p from '../../../utils/platform'
import locationBehavior from '../../../behaviors/location.js';
import { insertHouseLog } from '../../../common/log.js';
import {  } from '../../../common/log.js';
import * as transferData from '../../../models/transferData'

let qqmapsdk = mapConfig.qqmapsdk;

const app = getApp()
Page({
  behaviors: [locationBehavior],
  data: {
    choosefloor: -1,
    latitude: "",
    longitude: "",
    markers: [{
      iconPath: "/images/marker.png",
      id: 0,
      latitude: "",
      longitude: "",
      width: 20,
      height: 20,
    }],
    rows: [],
    loading: true,
    scale: 16,
    isChoseCity: false,
    hidden: false,
    subscription: false ,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //未开启定位退出页面
    wx.getSystemInfo({
      
      success( res ) {
        if(!res.locationEnabled&&res.locationEnabled!=undefined){
          wx.showModal({
            content: '请打开GPS后再使用！',
            showCancel: false,
            complete(res) {
              wx.navigateBack({
                delta: 1,
              })
            }
          })
        }
      }
    })
    var that = this;
    if(options.subscription){
      this.setData({
        subscription: true
      }) 
    }
    app.mobileLogin()
      .then(() => {
        var currentCity = wx.getStorageSync('currentCity');
        insertHouseLog({
          logType: "1",
          cityName: currentCity? currentCity.city : "上海市",
          inputHouseType: app.getCurrentStatusName()
        })

        wx.getSetting({
          success(res) {
            if (!res.authSetting['scope.userLocation']) {
              //已经授权
              wx.authorize({
                scope: 'scope.userLocation',
                success(data) {
                  that.getLoacalMap()


                  var currentCity = wx.getStorageSync('currentCity');
                  // debugger
                  if (currentCity.city) {
                    this.setData({
                      currentCity: currentCity
                    })
                  } else {
                    that.renderCity()
                  }
                },
                //已经拒绝授权
                fail() {
                  that.setData({
                    hidden: true,
                  })
                },
              })
            } else {
              var isChoseCity = wx.getStorageSync('isChoseCity')
              if (isChoseCity == false) {
                that.getLoacalMap()
              }

              var currentCity = wx.getStorageSync('currentCity');
              if (currentCity.city) {
                that.setData({
                  currentCity: currentCity
                })
              } else {
                that.renderCity()
              }
            }
          }
        })
      })
      .catch(() => {
        app.globalData.afterMobileAuthorCallBack = () => {
          wx.redirectTo({
            url: '/pages/addHouse/chooseHouse/chooseHouse',
          })
        }
      })
  },

  /**
   * 生命周期函数--监听页面显示
   */

  onShow: function() {
    var isChoseCity = wx.getStorageSync('isChoseCity')
    if (this.data.isChoseCity || isChoseCity) {
      var that = this
      var currentCity = wx.getStorageSync('currentCity');
      that.setData({
        currentCity: currentCity
      })

      if (currentCity.city) {
        qqmapsdk.geocoder({
          address: currentCity,
          success: (res) => {
            that.setData({
              latitude: res.result.location.lat,
              longitude: res.result.location.lng,
            })

            this.setData({
              loading: true,
            })

            this.getCurrentCityByLatlng(res.result.location.lat, res.result.location.lng)
              .then((res) => {
                return this.getVillageBe(res, this.data.subscription)
              })
              .then((rows) => {
                if(!this.data.subscription||rows.length == 0){
                  this.setData({
                    scale: 10,
                    rows,
                    loading: false,
                  })
                }else {
                  let rowId = [];
                  rows.map(v => rowId.push(v.hdResblockId))
                  api.subscribeList(rowId, res=> {
                    let contentId = res.data.content;
                    rows.map(n => {
                      let isSubscribe = contentId.find(o => {
                        return o== n.hdResblockId
                      })
                      if(isSubscribe){
                        n.subscribe = true
                      } else {
                        n.subscribe = false
                      }
                      this.setData({
                        scale: 10,
                        rows,
                        loading: false,
                      })
                    })
                  })
                }    
              })
          }
        })
      }
    }
  },
  // 视野发生变化时触发 获取中心点（即用户选择的位置）
  regionchange(e) {
    //只有拖动的情况下
    if (e.causedBy == "drag") {
      this.getCenterLngLat();
    }
  },
  //获取中心点经纬度
  getCenterLngLat: function() {
    let that = this;
    that.mapCtx = wx.createMapContext('map');
    that.mapCtx.getCenterLocation({
      success: (res) => {
        this.setData({
          loading: true,
        })


        // console.log("移动坐标", res.latitude, res.longitude);
        this.getCurrentCityByLatlng(res.latitude, res.longitude)
          .then((res) => {
            return this.getVillageBe(res, this.data.subscription)
          })
          .then((rows) => {
            if(!this.data.subscription||rows.length == 0){
              this.setData({
                rows,
                loading: false,
              })
            }else {
              let rowId = [];
              rows.map(v => rowId.push(v.hdResblockId))
              api.subscribeList(rowId, res=> {
                let contentId = res.data.content;
                rows.map(n => {
                  let isSubscribe = contentId.find(o => {
                    return o== n.hdResblockId
                  })
                  if(isSubscribe){
                    n.subscribe = true
                  } else {
                    n.subscribe = false
                  }
                  this.setData({
                    rows,
                    loading: false,
                  })
                })
              })
            }
          })
      }
    })
  },

  goSearchHouse() {
    if (this.data.choosefloor == 1) {
      wx.navigateTo({
        url: '/pages/addHouse/searchHouse/searchHouse?choosefloor=' + this.data.choosefloor,
      })
    } else {
      let subscribe = this.data.subscription ? 1 : 0;
      wx.navigateTo({
        url: `/pages/addHouse/searchHouse/searchHouse?subscribe=${subscribe}`,
      })
    }

  },
  goInfoEntryHouse(e) {
    let pageUrl = transferData.getData('selectHouseAreaEnterNextPage') || '/pages/addHouse/infoEntryHouse/infoEntryHouse'
    let villageData = e.currentTarget.dataset.village;
    p.navigateTo({
      url: `${pageUrl}?villageData=${JSON.stringify(villageData)}`
    })
  },
  goFloorStrategy() {
    wx.navigateTo({
      url: '/pages/mine/floorStrategy/floorStrategy',
    })
  },
  //选择城市
  goSwitchCity() {
    wx.navigateTo({
      url: '/pages/home/switchCity/switchCity',
    })
  },
  getLoacalMap() {
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      success: (res) => {
        //通过经纬度回去获取附近小区数据
        this.setData({
          loading: true,
        })
        this.getCurrentCityByLatlng(res.latitude, res.longitude)
          .then((res) => {
            return this.getVillageBe(res, this.data.subscription)
          })
          .then((rows) => {
            if(!this.data.subscription||rows.length == 0){
              this.setData({
                rows,
                loading: false,
              })
            }else {
              let rowId = [];
              rows.map(v => rowId.push(v.hdResblockId))
              api.subscribeList(rowId, res=> {
                let contentId = res.data.content;
                rows.map(n => {
                  let isSubscribe = contentId.find(o => {
                    return o== n.hdResblockId
                  })
                  if(isSubscribe){
                    n.subscribe = true
                  } else {
                    n.subscribe = false
                  }
                  this.setData({
                    rows,
                    loading: false,
                  })
                })
              })
            }
          })
        

        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          markers: [{
            iconPath: "/images/marker.png",
            id: 0,
            latitude: res.latitude,
            longitude: res.longitude,
            width: 20,
            height: 20,
          }],
        })
      }
    })
  },

  renderCity() {
    //获取地理位置
    // this.getWxLocationBe()
    //   .then((res) => {
    //     return this.getCurrentCityByLatlng(res.latitude, res.longitude)
    //   })
    //   .then((res) => {
    //     this.setData({
    //       currentCity: res
    //     })
    //     wx.setStorageSync('currentCity', res)
    //   })

    this.getCityInfoNew().then((res) => {
      this.setData({
        currentCity: res
      });
      resolve()
    })
  },

  confirmLoc() {
    var that = this;
    this.setData({
      hidden: false
    })
    wx.openSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          //还是没授权，给个默认
          that.setData({
            loading: false,
            latitude: "31.239580",
            longitude: "121.499763",
            currentCity: { "city": " 上海市" }
          })
        } else {
          that.getLoacalMap()
            //授权啦
        }
      }
    })
  },
  getSubscribe(e) {
    wx.showLoading({
      title: '订阅中...',
    })
    let sub = e.currentTarget.dataset.sub;
    let hdResblockId = e.currentTarget.dataset.hdresblockid;
    api.subscribe({
      hdResblockId,
      stated: sub,
    }, res => {
      wx.hideLoading()
      const {rows} = this.data
      transferData.setData('isRefreshMySubscribe', true)
      rows.forEach(item => {
        if(item.hdResblockId === hdResblockId) {
          item.subscribe = sub == 0 ? true : false
        }
      })
      this.setData({
        rows
      })
      // this.getCenterLngLat()
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    wx.removeStorageSync('lufangtiaozhuan')
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

    wx.setStorageSync('boole', false)

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  }
})